/*
 * Copyright 2016 Google Inc. All Rights Reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.google.errorprone;

import com.sun.tools.javac.file.JavacFileManager;
import com.sun.tools.javac.util.Context;

import java.net.URL;
import java.net.URLClassLoader;

import javax.tools.JavaFileManager;

/**
 * A classloader that allows plugins to access the Error Prone classes from the compiler classpath.
 */
// TODO(cushon): consolidate with Bazel's ClassLoaderMaskingPlugin
public class MaskedClassLoader extends ClassLoader {

  /**
   * An alternative to {@link JavacFileManager#preRegister(Context)} that installs a {@link
   * MaskedClassLoader}.
   */
  public static void preRegisterFileManager(Context context) {
    context.put(
        JavaFileManager.class,
        new Context.Factory<JavaFileManager>() {
          @Override
          public JavaFileManager make(Context c) {
            return new JavacFileManager(c, true, null) {
              @Override
              protected ClassLoader getClassLoader(URL[] urls) {
                return new URLClassLoader(
                    urls, new MaskedClassLoader(JavacFileManager.class.getClassLoader()));
              }
            };
          }
        });
  }

  public MaskedClassLoader(ClassLoader parent) {
    super(parent);
  }

  @Override
  protected Class<?> findClass(String name) throws ClassNotFoundException {
    int idx = name.lastIndexOf('.');
    if (idx == -1) {
      throw new ClassNotFoundException(name);
    }
    String packageName = name.substring(0, idx);
    switch (packageName) {
      case "com.google.errorprone":
      case "org.checkerframework.dataflow":
        return Class.forName(name);
      default:
        throw new ClassNotFoundException(name);
    }
  }
}
